package com.ruoyi.framework.netty.childhandler.chat;

import com.ruoyi.common.constant.heytalk.CommonConstants;
import com.ruoyi.common.core.domain.heytalk.netty.ChatMsg;
import com.ruoyi.common.core.domain.heytalk.netty.DataType;
import com.ruoyi.common.core.domain.heytalk.netty.UserChannelUtils;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.heytalk.ByteBufUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 单聊
 * @author zhusy
 * @since 2021/11/22
 */
@Slf4j
@ChannelHandler.Sharable
public class SingleChatHandler extends SimpleChannelInboundHandler<ChatMsg> {

    public static SingleChatHandler getInstance = new SingleChatHandler();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatMsg chatMsg) throws Exception {
        System.out.println("单聊消息msg======" + chatMsg.toString());
        Channel toUserChannel = UserChannelUtils.getChannel(chatMsg.getToId());
        //接收方不存在或socket不在线
        if (!Objects.isNull(toUserChannel) && UserChannelUtils.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(ByteBufUtils
                    .getByteBuf(DataType.builder()
                            .type(CommonConstants.DataTypeEnum.CHAT.getCode())
                            .data(chatMsg).build()));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
